﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Ex03.GarageManagementSystem.ConsoleUI
{
    public static class MenuGenerator
    {
        private const bool v_InterceptKey = true;

        private static string createMenuStringFromEnum(Type i_EnumType)
        {
            int i = 1;
            StringBuilder builder = new StringBuilder();

            foreach (string currentEnumName in Enum.GetNames(i_EnumType))
            {
                builder.Append(i.ToString()).Append(". ");
                builder.Append(currentEnumName).Append(Environment.NewLine);
                i++;
            }

            return builder.ToString();
        }

        public static Enum MenuFromEnum(Type i_EnumType, string i_Title)
        {
            string menuStr = createMenuStringFromEnum(i_EnumType);
            ConsoleKeyInfo menuSelection;

            Console.WriteLine(i_Title);
            Console.Write(menuStr);

            menuSelection = System.Console.ReadKey(v_InterceptKey);
            int result = menuSelection.KeyChar - '1'; 

            while (result >= Enum.GetNames(i_EnumType).Length || result < 0)
            {
                menuSelection = System.Console.ReadKey(v_InterceptKey);
                result = menuSelection.KeyChar - '1'; 
            }

            return (Enum) Enum.Parse(i_EnumType, Enum.GetNames(i_EnumType)[result]);
        }

        public static void FillOutDictionary(ref Dictionary<string, string> io_Dict)
        {
            Dictionary<string, string> newDictWithUserInput = new Dictionary<string, string>();

            foreach (string currentKey in io_Dict.Keys)
            {
                if (io_Dict[currentKey] == null)
                {
                    Console.Write(currentKey + ": ");
                    newDictWithUserInput.Add(currentKey, Console.ReadLine());
                }
                else
                {
                    newDictWithUserInput.Add(currentKey, io_Dict[currentKey]);
                }
            }

            io_Dict = newDictWithUserInput;
        }

        public static void WaitForKey()
        {
            Console.WriteLine("Press key to continue...");
            Console.ReadKey(v_InterceptKey);
        }

        public static float GetFloatFromUser(string i_Title)
        {
            float retFloat;
            Console.WriteLine(i_Title);
            string floatStrFromUser = Console.ReadLine();

            while (!float.TryParse(floatStrFromUser, out retFloat))
            {
                Console.WriteLine("Error, please type a number: ");
                floatStrFromUser = Console.ReadLine();
            }

            return retFloat;
        }
    }
}
